<template>
  <div class="request-definition-execute">
    <header class="mb-8">
      <div class="flex items-center">
        <router-link :to="`/request/definitions/${definitionId}`" class="mr-4 text-light-dark hover:text-primary">
          <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"></path>
          </svg>
        </router-link>
        <h1 class="glow-text">执行请求定义</h1>
      </div>
      <div class="tech-line mt-2"></div>
    </header>

    <div v-if="loading" class="flex justify-center items-center py-12">
      <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="!definition" class="text-center py-12 text-light-dark">
      未找到请求定义或加载失败
    </div>

    <div v-else class="grid grid-cols-1 lg:grid-cols-2 gap-8">
      <!-- 请求信息 -->
      <div class="card">
        <h2 class="text-xl font-medium mb-6">请求信息</h2>
        
        <div class="mb-4">
          <div class="text-light-dark mb-1">请求名称</div>
          <div class="text-lg font-medium">{{ definition.name }}</div>
        </div>
        
        <div class="mb-4">
          <div class="text-light-dark mb-1">请求方法</div>
          <span :class="{
            'badge badge-blue': definition.method === 'GET',
            'badge badge-green': definition.method === 'POST',
            'badge badge-purple': definition.method === 'PUT',
            'badge badge-orange': definition.method === 'DELETE',
            'badge badge-yellow': !['GET', 'POST', 'PUT', 'DELETE'].includes(definition.method)
          }">{{ definition.method }}</span>
        </div>
        
        <div class="mb-4">
          <div class="text-light-dark mb-1">请求 URL</div>
          <div class="font-mono break-all">{{ definition.url }}</div>
        </div>
        
        <div class="mb-6">
          <div class="text-light-dark mb-1">描述</div>
          <div>{{ definition.description || '无描述' }}</div>
        </div>
        
        <div class="mb-6">
          <div class="text-light-dark mb-2">请求头</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-60 overflow-y-auto">
            <pre>{{ formatHeaders(definition.headers) }}</pre>
          </div>
        </div>
        
        <div v-if="definition.body">
          <div class="text-light-dark mb-2">请求体</div>
          <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-60 overflow-y-auto">
            <pre>{{ formatBody(definition.body, definition.headers) }}</pre>
          </div>
        </div>
      </div>

      <!-- 执行结果 -->
      <div>
        <div class="card mb-6">
          <div class="flex justify-between items-center mb-6">
            <h2 class="text-xl font-medium">执行结果</h2>
            <button @click="executeRequest" class="btn btn-primary" :disabled="executing">
              <span v-if="executing">
                <svg class="animate-spin -ml-1 mr-2 h-4 w-4 inline-block" fill="none" viewBox="0 0 24 24">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                  <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                执行中...
              </span>
              <span v-else>
                <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"></path>
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                执行请求
              </span>
            </button>
          </div>

          <div v-if="!executionResult" class="text-center py-12 text-light-dark">
            点击"执行请求"按钮执行请求
          </div>

          <div v-else>
            <div class="mb-4">
              <div class="text-light-dark mb-1">状态码</div>
              <div :class="{
                'text-accent-blue': executionResult.status_code < 300,
                'text-accent-yellow': executionResult.status_code >= 300 && executionResult.status_code < 400,
                'text-accent-orange': executionResult.status_code >= 400 && executionResult.status_code < 500,
                'text-accent-pink': executionResult.status_code >= 500
              }">{{ executionResult.status_code }}</div>
            </div>

            <div class="mb-4">
              <div class="text-light-dark mb-1">响应时间</div>
              <div>{{ executionResult.response_time.toFixed(2) }} ms</div>
            </div>

            <div class="mb-4">
              <div class="text-light-dark mb-2">响应头</div>
              <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-40 overflow-y-auto">
                <pre>{{ formatHeaders(executionResult.headers) }}</pre>
              </div>
            </div>

            <div>
              <div class="text-light-dark mb-2">响应体</div>
              <div class="bg-dark-darker p-4 rounded-lg font-mono text-sm overflow-x-auto max-h-80 overflow-y-auto">
                <pre>{{ formatBody(executionResult.body) }}</pre>
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-between">
          <router-link :to="`/request/definitions/${definitionId}`" class="btn btn-outline">
            返回详情
          </router-link>
          <div class="flex space-x-2">
            <button 
              v-if="executionResult" 
              @click="saveResult" 
              class="btn btn-primary"
              :disabled="saving"
            >
              <span v-if="saving">保存中...</span>
              <span v-else>
                <svg class="w-5 h-5 mr-2 inline-block" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                </svg>
                保存结果
              </span>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { requestApi } from '../../api';

// 路由
const route = useRoute();
const router = useRouter();
const definitionId = route.params.id as string;

// 状态变量
const loading = ref(false);
const executing = ref(false);
const saving = ref(false);
const definition = ref<any>(null);
const executionResult = ref<any>(null);

// 获取请求定义详情
const fetchDefinitionDetail = async () => {
  try {
    loading.value = true;
    const response = await requestApi.getDefinitionById(definitionId);
    
    if (response && typeof response === 'object') {
      definition.value = response;
    } else {
      // 模拟数据
      definition.value = {
        _id: definitionId,
        name: '获取用户信息',
        method: 'GET',
        url: 'https://api.example.com/users/123',
        description: '获取指定ID的用户详细信息',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer token123'
        },
        body: null,
        created_at: new Date(Date.now() - 86400000).toISOString(),
        updated_at: new Date(Date.now() - 86400000).toISOString()
      };
    }
  } catch (error) {
    console.error('获取请求定义详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 执行请求
const executeRequest = async () => {
  try {
    executing.value = true;
    const response = await requestApi.executeDefinition(definitionId);
    
    if (response && typeof response === 'object') {
      executionResult.value = response;
    } else {
      // 模拟数据
      executionResult.value = {
        status_code: 200,
        response_time: 45.2,
        headers: {
          'Content-Type': 'application/json',
          'Cache-Control': 'no-cache',
          'X-Request-ID': '12345'
        },
        body: JSON.stringify({
          id: 123,
          name: 'John Doe',
          email: 'john@example.com',
          created_at: '2023-01-01T00:00:00Z'
        }),
        executed_at: new Date().toISOString()
      };
    }
  } catch (error: any) {
    console.error('执行请求失败:', error);
    
    // 模拟错误响应
    executionResult.value = {
      status_code: error.response?.status || 500,
      response_time: 32.1,
      headers: error.response?.headers || {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        error: error.response?.data?.error || '执行请求失败',
        message: error.message
      }),
      executed_at: new Date().toISOString()
    };
  } finally {
    executing.value = false;
  }
};

// 保存结果
const saveResult = async () => {
  try {
    saving.value = true;
    
    // 这里应该有一个保存结果的API，暂时使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    alert('结果已保存');
  } catch (error: any) {
    console.error('保存结果失败:', error);
    alert(`保存结果失败: ${error.response?.data?.error || error.message}`);
  } finally {
    saving.value = false;
  }
};

// 格式化请求头
const formatHeaders = (headers: any) => {
  if (!headers) return 'No headers';
  
  return Object.entries(headers)
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n');
};

// 格式化请求/响应体
const formatBody = (body: any, headers?: any) => {
  if (!body) return 'No body';
  
  // 检查内容类型
  const contentType = headers && headers['Content-Type'] ? headers['Content-Type'] : '';
  
  // 如果是 JSON
  if (contentType.includes('application/json') || typeof body === 'object') {
    try {
      // 如果已经是字符串，尝试解析它
      if (typeof body === 'string') {
        const parsed = JSON.parse(body);
        return JSON.stringify(parsed, null, 2);
      }
      // 如果已经是对象，直接格式化
      return JSON.stringify(body, null, 2);
    } catch (e) {
      // 如果解析失败，返回原始内容
      return body;
    }
  }
  
  // 其他类型直接返回
  return body;
};

// 生命周期钩子
onMounted(() => {
  fetchDefinitionDetail();
});
</script>

<style scoped>
/* 可以添加组件特定的样式 */
</style>
